use std::{cell::RefCell, rc::Rc, string};

use deno_core::{op2, v8, OpState};
use QcCore::{ecs::component::Named, scene_system::scene::Scene};
use QcUI::component::{Button, Canvas, ToUi};

use crate::utils::GoExt;

#[op2]
pub fn opAddChild<'a>(
    state: &mut OpState,
    scope: &mut v8::HandleScope<'a>,
    child: v8::Local<v8::Object>,
) -> v8::Local<'a, v8::Value> {
    let scene = state.borrow_mut::<*mut Scene>();
    let scene = unsafe { &mut **scene };

    if let Some(index) = scene.get_main_canvas() {
        if let Some(canvas) = scene[index].getComponentMut::<Canvas>() {
            if let Some(uuid) = GoExt::get_uuid(scope, child) {
                canvas.add_child_by_id(uuid)
            }
        }
    }

    v8::undefined(scope).into()
}

#[op2]
pub fn opAddChildWithParent<'a>(
    state: &mut OpState,
    scope: &mut v8::HandleScope<'a>,
    child: v8::Local<v8::Object>,
    parent: v8::Local<v8::Object>,
) -> v8::Local<'a, v8::Value> {
    let scene = state.borrow_mut::<*mut Scene>();
    let scene = unsafe { &mut **scene };

    if let Some(index) = scene.get_main_canvas() {
        if let Some(canvas) = scene[index].getComponentMut::<Canvas>() {
            if let Some(child_id) = GoExt::get_uuid(scope, child) {
                if let Some(parent_id) = GoExt::get_uuid(scope, child) {
                    canvas.add_child_with_parent_by_id(child_id, Some(parent_id));
                }
            }
        }
    }

    v8::undefined(scope).into()
}

#[op2]
pub fn opRemoveChild<'a>(
    state: &mut OpState,
    scope: &mut v8::HandleScope<'a>,
    child: v8::Local<v8::Object>,
) {
    let scene = state.borrow_mut::<*mut Scene>();
    let scene = unsafe { &mut **scene };

    if let Some(index) = scene.get_main_canvas() {
        if let Some(canvas) = scene[index].getComponentMut::<Canvas>() {
            if let Some(uuid) = GoExt::get_uuid(scope, child) {
                canvas.remove_child(index);
            }
        }
    }
}
